# -*- coding: utf-8 -*-

from django.utils.translation import gettext_lazy as _
from django.contrib.auth.hashers import make_password
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from apps.sys.models import User, Menu, Role
from apps.sys.user.serializers import *
from apps.sys.user.filters import *
from apps.sys.role.serializers import RoleSerializer
from core.viewset import CustomModelViewSet
from core.response import JsonResponse


class UserViewSet(CustomModelViewSet):
    """
    用户接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = User.objects.exclude(is_superuser=1).all()
    serializer_class = UserSerializer
    filterset_class = UserFilterSet
    create_serializer_class = UserCreateSerializer
    update_serializer_class = UserUpdateSerializer
    search_fields = ["username", "name", "gender", "dept__name", "role__name"]

    @action(detail=False, methods=["GET"], permission_classes=[IsAuthenticated])
    def get_info(self, request):
        """修改当前用户信息"""
        user = request.user
        data = {
            "permissions": ["*:*:*"],
            "roles": ["admin"],
            "user": {
                "id": user.id,
                "admin": user.is_superuser,
                "avatar": user.avatar,
                "create_time": user.create_time,
                "delFlag": "0",
                "email": user.email,
                "last_login": user.last_login,
                "name": user.name,
                "username": user.username,
            },
        }
        if not user.is_superuser:
            permissions_list = user.roles.values_list("menu__id", flat=True)
            permissions = (
                Menu.objects.filter(id__in=permissions_list)
                .exclude(perms=None)
                .values_list("perms", flat=True)
            )
            roles = user.roles.values_list("key", flat=True)
            data["permissions"] = permissions
            data["roles"] = roles
            data["user"] = UserSerializer(user, request=request).data
        return JsonResponse(data=data, msg="获取成功")

    @action(detail=False, methods=["GET"], permission_classes=[IsAuthenticated])
    def get_profile(self, request):
        """获取当前用户信息"""
        data = UserSerializer(request.user, request=request).data
        return JsonResponse(data=data, msg="获取成功")

    @action(detail=False, methods=["PUT"], permission_classes=[IsAuthenticated])
    def update_profile(self, request):
        """修改当前用户信息"""
        user = request.user
        User.objects.filter(id=user.id).update(**request.data)
        return JsonResponse(msg="修改成功")

    @action(detail=False, methods=["PUT"])
    def avatar(self, request, *args, **kwargs):
        """UserProfile上传用户图像"""
        return JsonResponse(msg="上传成功")

    @action(detail=True, methods=["PUT"], permission_classes=[IsAuthenticated])
    def change_password(self, request, *args, **kwargs):
        """密码修改"""
        instance = User.objects.filter(id=kwargs.get("pk")).first()
        data = request.data
        old_pwd = data.get("oldPassword")
        new_pwd = data.get("newPassword")
        new_pwd2 = data.get("newPassword2")
        if instance:
            if new_pwd != new_pwd2:
                return JsonResponse(msg="两次密码不匹配")
            elif instance.check_password(old_pwd):
                instance.password = make_password(new_pwd)
                instance.save()
                return JsonResponse(msg="修改成功")
            else:
                return JsonResponse(msg="旧密码不正确")
        else:
            return JsonResponse(msg="未获取到用户")

    @action(detail=True, methods=["PUT"], permission_classes=[IsAuthenticated])
    def change_status(self, request, *args, **kwargs):
        """修改状态"""
        instance = User.objects.filter(id=kwargs.get("pk")).first()
        if instance:
            instance.status = request.data["status"]
            instance.save()
            return JsonResponse(data={"status": instance.status}, msg="修改成功")
        else:
            return JsonResponse(msg="修改失败")

    @action(detail=True, methods=["PUT"], permission_classes=[IsAuthenticated])
    def reset_password(self, request, *args, **kwargs):
        """密码重置"""
        instance = User.objects.filter(id=kwargs.get("pk")).first()
        data = request.data
        new_pwd = data.get("newPassword")
        new_pwd2 = data.get("newPassword2")
        if instance:
            if new_pwd != new_pwd2:
                return JsonResponse(msg="两次密码不匹配")
            else:
                instance.password = make_password(new_pwd)
                instance.save()
                return JsonResponse(msg="修改成功")
        else:
            return JsonResponse(msg="未获取到用户")

    @action(detail=False, methods=["GET"])
    def get_related(self, request, *args, **kwargs):
        """通过用户id获取授权角色列表"""
        user = User.objects.get(id=request.query_params["userId"])
        serializer = RoleSerializer(user.roles, many=True)
        return JsonResponse(data=serializer.data)

    @action(detail=False, methods=["GET"])
    def get_unrelated(self, request, *args, **kwargs):
        """通过用户id获取未授权角色列表"""
        roles = Role.objects.exclude(user_set=request.query_params["userId"])
        serializer = RoleSerializer(roles, many=True)
        return JsonResponse(data=serializer.data)

    @action(detail=False, methods=["PUT"])
    def add_unrelated(self, request, *args, **kwargs):
        """通过用户id为所选角色授权"""
        user = User.objects.get(id=request.data.get("userId"))
        user.roles.add(*request.data.get("roleIds"))
        return JsonResponse(msg="添加授权成功")

    @action(detail=False, methods=["PUT"])
    def remove_related(self, request, *args, **kwargs):
        """通过用户id取消所有授权角色"""
        user = User.objects.get(id=request.data.get("userId"))
        user.roles.remove(*request.data.get("roleIds"))
        return JsonResponse(msg="取消授权成功")


class UserNotificationViewSet(CustomModelViewSet):
    """
    用户通知接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = UserNotification.objects.all()
    serializer_class = UserNotificationSerializer
    filterset_class = UserNotificationFilterSet

    def get_queryset(self):
        return UserNotification.objects.filter(user=self.request.user)

    @action(detail=False, methods=["get"])
    def unread_count(self, request):
        count = self.get_queryset().filter(is_read=False).count()
        data = {"unread_count": count}
        return JsonResponse(data=data)

    @action(detail=True, methods=["post"])
    def mark_read(self, request, pk=None):
        notification = self.get_object()
        notification.is_read = True
        notification.save()
        return JsonResponse(msg="标记已读成功")

    @action(detail=False, methods=["post"])
    def batch_read(self, request):
        updated = UserNotification.objects.filter(
            user=request.user, is_read=False
        ).update(is_read=True)
        return JsonResponse(msg="标记已读成功")
